from PyQt5.QtWidgets import (QLabel,
                             QLineEdit,
                             QPushButton,
                             QFileDialog,
                             QHBoxLayout, QVBoxLayout,
                             QComboBox, QWidget,
                             QTableView, QAbstractItemView, QHeaderView,
                             QMessageBox, QTableWidget, QTableWidgetItem)
from PyQt5.QtCore import Qt, QTimer, QDateTime
from PyQt5.QtGui import QStandardItemModel, QStandardItem, QIcon
import pandas as pd
import os

# from .Base import *
from ...NvmGenera.NvmGenePresenter import *
from workspace.Project.UI.ui_base.py_ui_abstract import AbstractUiView

class NvmGeneraView(AbstractUiView):
    def __init__(self, cwd):
        # super().__init__(name, '0.0.1')
        self.cwd = cwd
        super(NvmGeneraView, self).__init__(ui_name='Nvm', ui_version='v1.0.0')
        self._NvmInitUi()
        self.nvmgenerater = NvmGenerater()
        self._NvmSetTableModel()

        '''test'''
        # self.send_timer = QTimer(self)
        # self.send_timer.start(1000)
        self._NvmSetSignalSlot()
        self.nvmcfg_view = NvmConfigView(self.cwd)

    def _NvmInitUi(self):
        main_layout = QVBoxLayout()

        filter_type_label = QLabel('项目')
        self.filter_type_comboBox = QComboBox()
        self.filter_type_comboBox.addItems(['广汽', '长城'])
        self.filter_type_comboBox.setCurrentIndex(0)

        filter_labels = QLabel('输入文件：')
        self.filter_line_edit = QLineEdit()

        layout = QHBoxLayout()
        layout.addWidget(filter_type_label)
        layout.addWidget(self.filter_type_comboBox)
        layout.addWidget(filter_labels)
        layout.addWidget(self.filter_line_edit)
        main_layout.addLayout(layout)

        self.load_cfg_btn = QPushButton('加载配置')
        self.open_output_btn = QPushButton('打开生成代码文件夹')
        self.nvm_input_btn = QPushButton('导入NVM输入文件')
        self.genera_output_btn = QPushButton('生成NVM代码按钮')

        layout = QHBoxLayout()
        layout.addWidget(self.load_cfg_btn)
        layout.addWidget(self.open_output_btn)
        layout.addWidget(self.nvm_input_btn)
        layout.addWidget(self.genera_output_btn)
        layout.setSpacing(250)
        main_layout.addLayout(layout)

        layout = QVBoxLayout()
        self.table_view = QTableView()
        layout.addWidget(self.table_view)
        layout.setContentsMargins(0, 10, 0, 30)         # left top right bottom
        main_layout.addLayout(layout)

        '''test '''
        # self.sys_time_label = QLabel()
        # self.sys_time_label.setText('date_time')
        # self.sys_time_label.setAlignment(Qt.AlignRight)
        # layout = QVBoxLayout()
        # layout.addWidget(self.sys_time_label)
        # main_layout.addLayout(layout)

        self.setLayout(main_layout)

    def _NvmSetTableModel(self):
        self.table_model = QStandardItemModel()
        self.table_model.setHorizontalHeaderLabels(['DID', 'DID Name', 'DID Name_C', 'Length', 'Byte', 'Bit', 'Sig Name', 'Sig Name_c', 
                                                   'Sig Info', 'RangeMin', 'RangeMax', 'DefaultValue', 'TextValue'])
        self.table_view.setModel(self.table_model)
        self.table_view.setEditTriggers(QAbstractItemView.NoEditTriggers) #禁用表格编辑功能
        # self.table_view.setSelectionBehavior(QAbstractItemView.SelectionBehavior.SelectRows) #设置表格只能选择行
        self.table_view.horizontalHeader().setStyleSheet("QHeaderView::section{background-color:rgb(225,225,225);}")
        # self.table_view.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch) #设置表格自适应宽度
        # self.table_view.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)  # 去掉水平滚动条
        self._NvmSetTabviewColSize()
        self.table_view.setWordWrap(True)   # 自动换行

    def _NvmSetSignalSlot(self):
        self.open_output_btn.clicked.connect(self._NvmOpenOutputFloder)
        self.nvm_input_btn.clicked.connect(self._NvmOpenInputExcel)
        self.genera_output_btn.clicked.connect(self._NvmStartGenera)
        self.load_cfg_btn.clicked.connect(self._NvmOpenConfigView)
        self.nvmgenerater.Mysignal.connect(self.NvmInsertTableView)
        # self.send_timer.timeout.connect(self._NvmShowTime)
    
    def _NvmOpenOutputFloder(self):
        # current_path = r'C:\0-wanghao\8-Tool Operate\1.参考\04_NVM_tool\NVM'
        current_path = os.getcwd()
        current_path += r"\output\components\Nvm"
        # print(current_path)
        os.startfile(current_path)

    def _NvmOpenInputExcel(self):
        # QFileDialog.getOpenFileNames 打开多个文件
        file_path, file_type = QFileDialog.getOpenFileName(self, '选择Excel', '', '输入Excel(*.xlsx)')
        self.filter_line_edit.setText(file_path)
        self.filter_line_edit.setEnabled(False)
        if file_path == '':
            QMessageBox.about(self, '输入告警', '输入为空,清重新输入')
        else:
            self.nvmgenerater.NvmPreSetExcelPath(file_path)
    
    def _NvmStartGenera(self):
        self.excel_path = self.filter_line_edit.text()
        if self.excel_path == '':
            QMessageBox.about(self, '输入告警', '没有导入Excel,清重新输入')
        else:
            self.nvmgenerater.NvmPreStartGenera(self.excel_path)

    def _NvmOpenConfigFloder(self):
        nvmconfig_path = os.getcwd()
        nvmconfig_path += r'\project\configure\NvmGenere'
        os.startfile(nvmconfig_path)

    def NvmInsertTableView(self, row, col, data):
        self.table_model.setItem(row, col, QStandardItem(data))
        self.table_model.item(row, col).setTextAlignment(Qt.AlignCenter)
        self.table_view.resizeRowToContents(row)

    def _NvmSetTabviewColSize(self):
        self.table_view.setColumnWidth(0, 80)
        self.table_view.setColumnWidth(1, 150)
        self.table_view.setColumnWidth(3, 70)
        self.table_view.setColumnWidth(4, 70)
        self.table_view.setColumnWidth(5, 70)
        self.table_view.setColumnWidth(6, 300)
        # self.table_view.setColumnWidth(7, 70)
        self.table_view.setColumnWidth(8, 380)
        self.table_view.setColumnWidth(9, 120)
        self.table_view.setColumnWidth(10, 120)
        self.table_view.setColumnWidth(11, 120)
        self.table_view.setColumnWidth(12, 120)

    def _NvmOpenConfigView(self):
        self.nvmcfg_view.show()

    # def _NvmShowTime(self):
    #     time = QDateTime.currentDateTime()
    #     self.sys_time = time.toString('yyyy-MM-dd hh:mm:ss dddd')
    #     self.sys_time_label.setText(self.sys_time)

class  NvmConfigView(AbstractUiView):
    def __init__(self, cwd):
        super(NvmConfigView, self).__init__(ui_name='Nvm_Cfg', ui_version='v1.0.0')
        self.setWindowTitle('Nvm配置')
        self.resize(400, 750)
        self.setWindowIcon(QIcon('./resource/spyder.ico'))
        self.nvmgenerater = NvmGenerater()
        self._NvmConfigSetUi()
        self._NvmConfigAddConfigValue()

    def _NvmConfigSetUi(self): 
        cfg_layout = QVBoxLayout()
        self.tableWdiget = QTableWidget()
        self.tableWdiget.setColumnCount(2)
        # self.tableWdiget.setRowCount(19)
        self.tableWdiget.setHorizontalHeaderLabels(['变量', '属性']) 
        self.tableWdiget.setEditTriggers(QTableWidget.NoEditTriggers)
        self.tableWdiget.horizontalHeader().setStyleSheet("QHeaderView::section{background-color:rgb(225,225,225);}")
        self.tableWdiget.horizontalHeader().setStretchLastSection(True)
        # QTableWidget.resizeRowsToContents(self.tableWdiget)
        # QTableWidget.resizeColumnsToContents(self.tableWdiget)
        self.tableWdiget.setAlternatingRowColors(True)
        self.tableWdiget.setColumnWidth(0, 150)
        # self.tableWdiget.setColumnWidth(1, 250)
        self.tableWdiget.clearContents()
        cfg_layout.addWidget(self.tableWdiget)                         # 行是否自动交替变色
        self.setLayout(cfg_layout)

    def _NvmConfigAddConfigValue(self):
        self.GolalConfigDict = self.nvmgenerater.NvmPreGetGlobalConfigDict()
        row = self.tableWdiget.rowCount()
        for key, value in self.GolalConfigDict.items():
            self.tableWdiget.insertRow(row)
            # print(row, key, value)
            self.tableWdiget.setItem(row, 0, QTableWidgetItem(key))
            self.tableWdiget.setItem(row, 1, QTableWidgetItem(str(value)))
            self.tableWdiget.item(row, 1).setTextAlignment(Qt.AlignCenter)
            self.tableWdiget.setRowHeight(row, 30)
            row += 1